<template>
  <div class="tm-const-list">
    <div class="const-list">
      <div class="const-list-item">
        变量名
      </div>
      <div class="const-list-item">
        变量值
      </div>
      <div class="const-list-ctrl">
      </div>
    </div>
    <div class="const-list"
         v-for="(value, key) in constants"
         :key="key"
         :class="{selected: key === currValue}"
         @click="onSelect(key)"
    >
      <div class="const-list-item">{{key}}</div>
      <div class="const-list-item">{{value}}</div>
      <div class="const-list-ctrl">
        <i class="el-icon-delete" @click.stop="onRemove(key)"></i>
      </div>
    </div>
    <div class="const-list">
      <div class="const-list-item">
        <el-input size="mini" v-model="key" placeholder="请输入"/>
      </div>
      <div class="const-list-item">
        <el-input size="mini" v-model="val" placeholder="请输入"/>
      </div>
      <div class="const-list-ctrl">
        <i class="el-icon-check" @click="onAdd"></i>
      </div>
    </div>
  </div>
</template>

<script>
import bus from '@/utils/bus'

export default {
  name: 'tm-const-list',
  cnName: '全局变量',
  props: {
    value: String,
    constants: Object
  },
  data() {
    return {
      currValue: this.value,
      key: '',
      val: ''
    }
  },
  watch: {
    value() {
      this.currValue = this.value
    }
  },
  methods: {
    onAdd() {
      if(!this.key) {
        return
      }
      bus.$emit('update-constants', this.key, this.val)
      this.key = ''
      this.val = ''
    },
    onRemove(key) {
      if(this.currValue === key) {
        this.currValue = ''
        this.$emit('input', this.currValue)
      }
      bus.$emit('delete-constants', key)
    },
    onSelect(key) {
      this.$emit('input', key)
    }
  }
}
</script>

<style lang="less" scoped>
.tm-const-list {
  border: 1px solid var(--input-bd-color);
  box-sizing: border-box;
  color: var(--text-color);
  border-radius: 4px;

  .const-list {
    display: flex;
    padding: 5px;
    border-bottom: 1px solid var(--input-bd-color);

    &.selected {
      background-color: var(--menu-active-bg);
    }

    &-item {
      flex: 1;
      padding: 0 5px;
    }
    &-ctrl {
      padding: 0 5px;
      width: 20px;
      cursor: pointer;
    }
  }
}
</style>
